package com.wyc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyc.dto.LoginFormDTO;
import com.wyc.dto.Result;
import com.wyc.dto.UserDTO;
import com.wyc.entity.User;
import com.wyc.mapper.UserMapper;
import com.wyc.service.IUserService;
import com.wyc.utils.RegexUtils;
import com.wyc.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.wyc.utils.RedisConstants.*;
import static com.wyc.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * 
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result singCount() {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        // 写入redis
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth, true);
        // 获取本月到今天的 所有签到记录
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(Collections.emptyList());
        }

        // 生成签到状态列表
        List<Boolean> signStatusList = new ArrayList<>(dayOfMonth);
        long count = 0;
        for (int i = 0; i < dayOfMonth; i++) {
            boolean signed = (num & 1) == 1;
            signStatusList.add(signed);
            if (signed) {
                count++;
            }
            num >>>= 1;
        }

        // 反转列表（确保高位对应第1天）
        Collections.reverse(signStatusList);

        return Result.ok(signStatusList, count);
    }

    @Override
    public Result sign() {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        // 写入redis
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();

    }

    public Result sendCode(String phone, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 不符合返回错误信息
            return Result.fail("手机号码格式错误!");
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 保存验证码到 redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 向前端发送验证码
        log.debug("验证码为{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 如果不匹配，直接返回错误
            return Result.fail("手机号码格式错误");
        }
        // 校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            // 验证码不一致
            return Result.fail("验证码错误");
        }
        // 验证成功，查询用户是否存在
        User user = query().eq("phone", phone).one();
        if (user == null) {
            // 不存在，创建新用户
            user = createUserWithPhone(phone);
        }

        String token = UUID.randomUUID().toString();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);

        // Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        // // 保存用户信息到redis
        // String key = LOGIN_USER_KEY + token;
        // stringRedisTemplate.opsForHash().putAll(key, userMap);

        // stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        // 创建用户
        User user = new User();
        user.setPhone(phone);
        user.setPassword(null);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(10));

        // 保存用户
        save(user);
        return user;
    }

    @Override
    public Result logout(String token) {
        // 删除Redis中的用户信息
        stringRedisTemplate.delete(LOGIN_USER_KEY + token);
        // 清除ThreadLocal中的用户数据
        UserHolder.removeUser();
        return Result.ok();
    }
}
